package com.xykj.enterprise.wechat.wap.service.identity;

import com.xykj.enterprise.wechat.base.config.JwtConfig;
import com.xykj.enterprise.wechat.base.web.domain.AjaxData;
import com.xykj.enterprise.wechat.bean.ext.identity.UserInfo3rd;
import com.xykj.enterprise.wechat.bean.wap.TokenVo;
import com.xykj.enterprise.wechat.util.other.TokenKeyUtil;
import com.xykj.enterprise.wechat.wap.service.BaseService;
import com.ydn.appserver.MinaAppClient;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.simplecache.SimpleCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhouxu
 * @create 2021-03-29 22:29
 */
@Service
@Slf4j
public class IdentityService extends BaseService {

    @Autowired
    private MinaAppClient busiClient;
    @Autowired
    private JwtConfig jwtConfig;
    @Autowired
    private SimpleCache simpleCache;

    @Value("${wx.saas.SuiteID}")
    private String SuiteID;
    @Value("${wx.saas.Secret}")
    private String Secret;
    @Value("${wx.saas.CorpID}")
    private String CorpID;
    @Value("${wx.saas.AgentID}")
    private Integer AgentID;


    public AjaxData generateWeComUserAuthUrl(String redirectUri, String state) {
        Request request = new Request("GenerateWeComUserAuthUrl");
        request.setParameter("appId", CorpID);
        request.setParameter("agentId", SuiteID);
        request.setParameter("redirectUri", redirectUri);
        request.setParameter("state", state);
        return convertData(busiClient.send(request));
    }

    public AjaxData generateWeComEnterpriseAuthUrl(String redirectUri, String state) {
        Request request = new Request("GenerateWeComEnterpriseAuthUrl");
        request.setParameter("redirectUri", redirectUri);
        request.setParameter("state", state);
        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);
        return convertData(busiClient.send(request));
    }

    public AjaxData generatePermanentCode(String authCode) {
        Request request = new Request("GeneratePermanentCode");
        request.setParameter("authCode", authCode);
        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);
        return convertData(busiClient.send(request));
    }

    public AjaxData<TokenVo> loginByCode(String code) {
        Request request = new Request("LoginByCode");
        request.setParameter("code", code);
        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);
        Response response = busiClient.send(request);
        log.debug(response.getOriginalJson());

        // 根据 userid 生成 token
        if (response.isSuccess()) {
            UserInfo3rd userInfo3rd = response.getData().get("data", UserInfo3rd.class);

            Map<String, Object> param = new HashMap<>();
            param.put("userid", userInfo3rd.getUserId());
            param.put("corpid", userInfo3rd.getCorpId());
            String token = jwtConfig.newToken(param);

            int ttl = Integer.parseInt(String.valueOf(jwtConfig.getExpire()));

            simpleCache.put(TokenKeyUtil.get(userInfo3rd.getUserId(), userInfo3rd.getCorpId()), token, ttl);
            log.debug("token:{},userid:{},corpid:{},ttl:{}", token, userInfo3rd.getUserId(), userInfo3rd.getCorpId(), ttl);

            TokenVo tokenVo = new TokenVo();
            tokenVo.setToken(token);
            tokenVo.setUserid(userInfo3rd.getUserId());
            return AjaxData.success(tokenVo);
        } else {
            return AjaxData.failure(response.getCode(), response.getMessage());
        }
    }


    public AjaxData getAgentConfig(String url) {
        Request request = new Request("GetAgentConfig");
        request.setParameter("corpid", CorpID);
        request.setParameter("agent_id", AgentID);
        request.setParameter("url", url);
        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);
        return convertData(busiClient.send(request));
    }

    public AjaxData getConfig(String url) {
        Request request = new Request("GetConfig");
        request.setParameter("corpid", CorpID);
        request.setParameter("agent_id", AgentID);
        request.setParameter("url", url);
        request.setParameter("suite_id", SuiteID);
        request.setParameter("secret", Secret);
        return convertData(busiClient.send(request));
    }

}
